from rest_framework import serializers
from .models import User, Role, Permission, Menu


class PermissionSerializer(serializers.ModelSerializer):
    """权限序列化器"""
    class Meta:
        model = Permission
        fields = '__all__'


class RoleSerializer(serializers.ModelSerializer):
    """角色序列化器"""
    permissions = PermissionSerializer(many=True, read_only=True)
    permission_ids = serializers.ListField(
        child=serializers.IntegerField(), write_only=True, required=False
    )

    class Meta:
        model = Role
        fields = '__all__'

    def create(self, validated_data):
        permission_ids = validated_data.pop('permission_ids', [])
        role = Role.objects.create(**validated_data)
        if permission_ids:
            permissions = Permission.objects.filter(id__in=permission_ids)
            role.permissions.set(permissions)
        return role

    def update(self, instance, validated_data):
        permission_ids = validated_data.pop('permission_ids', None)
        for attr, value in validated_data.items():
            setattr(instance, attr, value)
        instance.save()
        
        if permission_ids is not None:
            permissions = Permission.objects.filter(id__in=permission_ids)
            instance.permissions.set(permissions)
        
        return instance


# UserRole序列化器已移除，使用Django内置的ManyToMany关系


class MenuSerializer(serializers.ModelSerializer):
    """菜单序列化器"""
    children = serializers.SerializerMethodField()
    permissions = PermissionSerializer(many=True, read_only=True)
    permission_ids = serializers.ListField(
        child=serializers.IntegerField(), write_only=True, required=False
    )
    parent_name = serializers.CharField(source='parent.name', read_only=True)

    class Meta:
        model = Menu
        fields = '__all__'

    def get_children(self, obj):
        """获取子菜单"""
        children = Menu.objects.filter(parent=obj, is_active=True).order_by('sort_order')
        return MenuSerializer(children, many=True).data

    def create(self, validated_data):
        permission_ids = validated_data.pop('permission_ids', [])
        menu = Menu.objects.create(**validated_data)
        if permission_ids:
            permissions = Permission.objects.filter(id__in=permission_ids)
            menu.permissions.set(permissions)
        return menu

    def update(self, instance, validated_data):
        permission_ids = validated_data.pop('permission_ids', None)
        for attr, value in validated_data.items():
            setattr(instance, attr, value)
        instance.save()
        
        if permission_ids is not None:
            permissions = Permission.objects.filter(id__in=permission_ids)
            instance.permissions.set(permissions)
        
        return instance


class UserManagementSerializer(serializers.ModelSerializer):
    """用户管理序列化器"""
    roles = RoleSerializer(many=True, read_only=True)
    role_ids = serializers.ListField(
        child=serializers.IntegerField(), write_only=True, required=False
    )

    class Meta:
        model = User
        fields = ('id', 'username', 'email', 'phone', 'avatar', 'is_active', 
                 'date_joined', 'roles', 'role_ids')

    def update(self, instance, validated_data):
        role_ids = validated_data.pop('role_ids', None)
        for attr, value in validated_data.items():
            setattr(instance, attr, value)
        instance.save()
        
        if role_ids is not None:
            # 使用Django内置的ManyToMany关系
            roles = Role.objects.filter(id__in=role_ids)
            instance.roles.set(roles)
        
        return instance
